"""
人脸识别及追踪
"""
import cv2


def read_img(cap, face_detector):
    while True:
        ret, frame = cap.read()
        grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        # # 检测人脸
        faces = face_detector.detectMultiScale(grey)
        if len(faces) > 0:
            x, y, w, h = faces[0]
            print(x, y, w, h)
            if w * h < 100 * 100:
                continue
            else:
                track_window = (x, y, w, h)
                roi = frame[x:x + w, y:y + h]
                print("face")
                return roi, track_window
                break
        else:
            print("no face")

 # 1.创建相机
cap = cv2.VideoCapture(0)
# 加载特征文件
face_detector = cv2.CascadeClassifier('./haarcascades/haarcascade_frontalface_default.xml')
roi, track_window = read_img(cap, face_detector)
print(track_window)

# 2-3.转换色彩空间
hsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
# 计算直方图
roi_hist = cv2.calcHist([hsv_roi], [0], None, [180], [0, 180])
# 归一化
cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)

# 2-4.目标追踪
# 设置窗口搜索终止条件：最大迭代次数，窗口中心漂移最小值
term_crit = (cv2.TermCriteria_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)

while True:
    ret, frame = cap.read()
    # 正常读取
    if ret:
        # 计算直方图的反向投影
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        dst = cv2.calcBackProject([hsv], [0], roi_hist, [0, 180], 1)

        # 进行meanshift追踪
        ret, track_window = cv2.meanShift(dst, track_window, term_crit)

        # 将追踪的位置绘制在视频上，并进行显示
        x, y, w, h = track_window
        img = cv2.rectangle(frame, (x, y), (x + w, y + h), 255, 2)
        cv2.imshow("frame", img)

        if cv2.waitKey(10) & 0xFF == ord('q'):
            break
    # 读取失败退出
    else:
        break

# 3.资源释放
cap.release()
cv2.destroyAllWindows()
